package com.daykw.xiaohongshu.task.thread;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.codehaus.plexus.util.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.impl.NutDao;

import com.daykw.xiaohongshu.http.HttpBase;
import com.daykw.xiaohongshu.model.TArticleTask;
import com.daykw.xiaohongshu.model.TAuthorTask;
import com.daykw.xiaohongshu.model.TKeywordNextTask;
import com.daykw.xiaohongshu.model.TKeywordTask;
import com.daykw.xiaohongshu.model.TSessionId;
import com.daykw.xiaohongshu.util.SessionUtils;
import com.daykw.xiaohongshu.util.SpringContextHolder;

public class KeywordNextJobThread implements Runnable {

	private static Logger logger = Logger.getLogger(KeywordNextJobThread.class);
	private TKeywordNextTask task;
	private String ip;
	private Integer port;
	private final static String REQUEST_ID = "dd633fd130f4edc18db5231513b748ed";

	public KeywordNextJobThread(TKeywordNextTask task) {
		this.task = task;
	}

	public KeywordNextJobThread(TKeywordNextTask task, String ip) {
		this.task = task;
		this.ip = ip.split(":")[0];
		this.port = Integer.valueOf(ip.split(":")[1]);
	}

	@Override
	public void run() {
		NutDao dao = SpringContextHolder.getBean("dao");
		try {
			dao.update(TKeywordNextTask.class, Chain.make("status", 1), Cnd.where("id", "=", task.getId()));
			String k = java.net.URLEncoder.encode(task.getKeyword(), "utf-8");
			// http://www.xiaohongshu.com/web_api/sns/v2/search/note?keyword=%E6%9D%8E%E5%B0%8F%E7%92%90&page=2
			
			
//			GET https://www.xiaohongshu.com/wx_mp_api/sns/v1/search/notes?sid=session.1214697449282265726&keyword=%E4%B8%83%E5%A4%95%E7%A4%BC%E7%89%A9&sort=general&page=2&per_page=20 HTTP/1.1
//				Host: www.xiaohongshu.com
//				Content-Type: application/json
//				Accept: */*
//				User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/16A5339e MicroMessenger/6.7.1 NetType/WIFI Language/zh_CN
//				Referer: https://servicewechat.com/wxffc08ac7df482a27/68/page-frame.html
//				Accept-Language: zh-cn
//				Accept-Encoding: br, gzip, deflate

			TSessionId sid = SessionUtils.Session.session.getQueue();
			String url = "https://www.xiaohongshu.com/wx_mp_api/sns/v1/search/notes?sid="+sid.getSid()+"&keyword=" + k + "&sort=general&page="+task.getPage_index()+"&per_page=20";
			HttpBase http = new HttpBase();
			Map<String, String> headers = new HashMap<String, String>();
			headers.put("Host","www.xiaohongshu.com");
			headers.put("Content-Type","application/json");
			headers.put("Accept","*/*");
			headers.put("User-Agent","Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/16A5339e MicroMessenger/6.7.1 NetType/WIFI Language/zh_CN");
			headers.put("Referer","https://servicewechat.com/wxffc08ac7df482a27/68/page-frame.html");
			headers.put("Accept-Language","zh-cn");
			headers.put("Accept-Encoding","br, gzip, deflate");
			
			
			// String html = http.request(url, "utf-8",
			// headers,ip,port).getResult();
			String html = http.get(url, "utf-8", headers, true);
			while ((StringUtils.isEmpty(html) || html.equals("fail"))
					|| (StringUtils.isNotEmpty(html) && html.indexOf("403 Forbidden") >= 0)) {
				//html = http.turl(url, "utf-8", headers, true);
				html = http.get(url, "utf-8", headers, true);
				//logger.error("################警告403 Forbidden IP封锁############");
				//dao.update(TKeywordNextTask.class, Chain.make("status", 3), Cnd.where("id", "=", task.getId()));
				//return;
			}
			
			if(html.equals("404")){
				dao.update(TKeywordNextTask.class, Chain.make("status", 3), Cnd.where("id", "=", task.getId()));
				return;
			}
			
			JSONObject json = null;
			try {
				json = new JSONObject(html);
			} catch (Exception e) {
				dao.update(TKeywordNextTask.class, Chain.make("status", 3), Cnd.where("id", "=", task.getId()));
				return;
			}

			JSONArray list = json.getJSONObject("data").getJSONArray("notes");
			int size = list.length();
			TArticleTask at;
			TAuthorTask aut;
			for (int i = 0; i < size; i++) {
				at = new TArticleTask();
				JSONObject d = list.getJSONObject(i);
				String aid = d.getString("id");
				if(StringUtils.isEmpty(aid) || aid.length() != 24){
					continue;
				}
				at.setAid(aid);
				at.setCreate_time(new Date());
				at.setComment_status(0);
				at.setStatus(0);
				// at.setTitle(d.getString("title"));
				at.setUrl("http://www.xiaohongshu.com/discovery/item/" + d.getString("id"));
				String user_id = d.getJSONObject("user").getString("userid");
				if(StringUtils.isEmpty(user_id) || user_id.length() != 24){
					continue;
				}
				at.setUser_id(user_id);
				try {
					dao.fastInsert(at);
				} catch (Exception e) {
					dao.update(TArticleTask.class,Chain.make("comment_status", 0),Cnd.where("aid", "=",at.getAid()));
					// e.printStackTrace();
					// logger.error("插入TArticleTask失败.", e);
				}
				aut = new TAuthorTask();
				aut.setCreate_time(new Date());
				aut.setStatus(0);
				aut.setUser_id(user_id);
				try {
					dao.fastInsert(aut);
				} catch (Exception e) {
					// e.printStackTrace();
					// logger.error("插入TAuthorTask失败.", e);
				}
			}
			dao.update(TKeywordNextTask.class, Chain.make("status", 2), Cnd.where("id", "=", task.getId()));
			logger.info("处理成功:"+url);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("处理TKeywordNextTask任务失败.", e);
			dao.update(TKeywordNextTask.class, Chain.make("status", 3), Cnd.where("id", "=", task.getId()));
		}

	}

}
